package cn.lanqiao.bigDate.web.controller;



import cn.hutool.core.collection.CollectionUtil;
import cn.lanqiao.bigDate.entity.sys.SysArea;
import cn.lanqiao.bigDate.entity.sys.SysDept;
import cn.lanqiao.bigDate.entity.sys.SysRole;
import cn.lanqiao.bigDate.reslut.Result;
import cn.lanqiao.bigDate.web.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(SysAreaController.BASE_URL)
public class SysAreaController extends BaseController {

    public static final String BASE_URL = "sysArea";

    /**
     * 页面跳转
     * @return  页面mav
     */
    @RequestMapping(value = "toIndex")
    public ModelAndView toIndex() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName(BASE_URL + "/index"); //指定路径
        return mav;
    }

    /**
     * 分页查询
     * @return  分页结果
     */
    @GetMapping(value = "findSysAreaPage")
    public IPage<SysArea> findByPage(Page<SysArea> page, String str) {
        return sysAreaService.findByPage(page,str);
    }

    /**
     * 查询所有数据
     * @return
     */
    @GetMapping(value = "findAllSysAreaData")
    public List<SysArea> findAll() {
        return sysAreaService.findAll();
    }

    /**
     * 按ID查询区域
     * @return  结果
     */
    @GetMapping(value = "findSysAreaOne")
    public SysArea findSysAreaOne(String id) {
        return sysAreaService.findSysAreaOne(id);
    }


    /**
     * 修改区域信息
     * @param sysArea
     * @return
     */
    @PostMapping(value = "updateSysArea")
    public Result findItemOne(SysArea sysArea) {
        Result reslut = new Result();
        Boolean isSuccess = sysAreaService.updateSysArea(sysArea);
        //调用校验工具
        Map<String, String> validate = ValidatorUtil.validate(sysArea);
        if (validate.isEmpty()) {
            if (isSuccess) {
                reslut.setCode(200);
                reslut.setMsg("修改成功");
            } else {
                reslut.setCode(500);
                reslut.setMsg("修改失败");
            }
        }else {
            reslut.setCode(300);
            reslut.setData(validate);
        }
        return reslut;
    }

    /**
     * 添加用户信息
     * @param sysArea
     * @return
     */
    @PostMapping(value = "saveSysArea")
    public Result saveItem(SysArea sysArea) {
        System.out.println(sysArea);
        Result reslut = new Result();
        //调用校验工具
        Map<String, String> validate = ValidatorUtil.validate(sysArea);
        if(validate.isEmpty()) {
            Boolean isSuccess = sysAreaService.saveSysArea(sysArea);
            if (isSuccess) {
                reslut.setCode(200);
                reslut.setMsg("添加成功");
            } else {
                reslut.setCode(500);
                reslut.setMsg("添加失败");
            }
        }else{
            reslut.setCode(300);
            reslut.setData(validate);
        }
        return reslut;
    }

    /**
     * 按id删除区域
     * @param ids
     * @return
     */
    @RequestMapping(value = "deleteSysArea")
    public Result<String> deleteItem(String ids) {
        Result<String> reslut = new Result();
        Boolean isSuccess = sysAreaService.deleteSysArea(ids);
        if(isSuccess){
            reslut.setCode(200);
            reslut.setMsg("删除成功");
        }else{
            reslut.setCode(500);
            reslut.setMsg("删除失败");
        }
        return reslut;
    }

    /**
     * 数据下载
     * @param
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping("downloadExcel")
    public void outPutExcel (HttpServletResponse response) throws IOException {
        //每次写100行数据，刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        Sheet sheet = wb.createSheet();
        //业务数据
        List<SysArea> list = sysAreaService.findAll();
        //获取表头字段
        List<String> collect = Arrays.stream(SysArea.class.getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
        //String[] titles = {"id","role_name","create_by","create_time","update_by","update_time","remark"};
        Row row = sheet.createRow(0);
        //删除不需要的表头字段
        collect.remove(0);
        collect.remove(collect.size()-1);
        //设置第一行标题
        for (int i = 0; i < collect.size(); i++) {
            String title = collect.get(i);
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
        }
        //导出数据
        for (int i = 0; i <list.size() ; i++) {
            Row rowData = sheet.createRow(i + 1);
            //实体类  通过实体类填写数据
            SysArea sysArea = list.get(i);
            //第一列 数据
            Cell cellDataA = rowData.createCell(0);
            cellDataA.setCellValue(sysArea.getId());
            //第二列 数据
            Cell cellDataB = rowData.createCell(1);
            cellDataB.setCellValue(sysArea.getLevel());
            //第三列 数据
            Cell cellDataC = rowData.createCell(2);
            cellDataC.setCellValue(sysArea.getParentCode());
            //第四列 数据
            Cell cellDataD = rowData.createCell(3);
            cellDataD.setCellValue(sysArea.getAreaCode());
            //第五列 数据
            Cell cellDataE = rowData.createCell(4);
            cellDataE.setCellValue(sysArea.getZipCode());
            //第六列 数据
            Cell cellDataF = rowData.createCell(5);
            cellDataF.setCellValue(sysArea.getCityCode());
            //第七列 数据
            Cell cellDataG = rowData.createCell(6);
            cellDataG.setCellValue(sysArea.getName());
            //第八列 数据
            Cell cellDataH = rowData.createCell(7);
            cellDataH.setCellValue(sysArea.getShortName());
            //第九列 数据
            Cell cellDataI = rowData.createCell(8);
            cellDataI.setCellValue(sysArea.getMergerName());
            System.out.println(sysArea.getMergerName());
            //第十列 数据
            Cell cellDataJ = rowData.createCell(9);
            cellDataJ.setCellValue(sysArea.getPinyin());
            //第十一列 数据
            Cell cellDataK = rowData.createCell(10);
            if (null!=sysArea.getLng()){
                cellDataK.setCellValue(sysArea.getLng().toString());
            }
            //第十二列 数据
            Cell cellDataL = rowData.createCell(11);
            if (null!=sysArea.getLat()) {
                cellDataL.setCellValue(sysArea.getLat().toString());
            }

        }
        String fileName = "区域数据.xlsx";
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        wb.write(response.getOutputStream());
        wb.close();
    }

    /**
     * 数据上传
     * @param request
     * @return
     */
    @PostMapping(value = "importAreaExcel")
    public Result<String> importOrderData(HttpServletRequest request) {
        Result<String> result = new Result<>();
        if (!(request instanceof MultipartHttpServletRequest)) {
            result.setCode(200);
            return result;
        }
        try {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                    .getFiles("file-2");
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                long size = file.getSize();
                if (size == 0) {
                    result.setCode(500);
                    result.setMsg("文件为空");
                    return result;
                }
                String[] name = fileName.split("\\.");
                //默认为高级版excel
                int type = 1;
                if ("xls".equals(name[1])) {
                    type = 2;
                }
                List<SysArea> sheet1 = excelService.readExcelOfList(file.getInputStream(), "sheet1", SysArea.class);
                for (SysArea sysArea : sheet1) {
                    if (ValidatorUtil.validate(sysArea).isEmpty()){
                        sysAreaService.addArea(sysArea);
                    }
                }
                System.out.println(sheet1);
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg(e.getMessage());
        }
        return result;
    }



}
